package com.qingyun.system.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qingyun.system.common.result.Result;
import com.qingyun.system.model.dto.FileInfo;
import com.qingyun.system.model.dto.RealCopanyRequest;
import com.qingyun.system.model.entity.Company;
import com.qingyun.system.model.entity.SysDept;
import com.qingyun.system.model.form.CompanyForm;
import com.qingyun.system.model.form.DeptForm;
import com.qingyun.system.model.form.UserForm;
import com.qingyun.system.model.query.CompanyPageQuery;
import com.qingyun.system.model.query.CompanyQueys;
import com.qingyun.system.model.validator.AddGroup;
import com.qingyun.system.model.vo.CompanyVO;
import com.qingyun.system.model.vo.PageVO;
import com.qingyun.system.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/v1/company")
@Tag(name="00.公司管理模块接口")
public class CompanyController {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysDeptService sysDeptService;

    @Resource
    private  CompanyService companyService;

    @Resource
    private SysUserRoleService sysUserRoleService;

    @Resource
    private OssService ossService;

    @Resource
    private BaiduAIService baiduAIService;


    @Value("${userrole.company}")
    private Long companyRole;
    @Value("${userrole.service}")
    private Long serviceRole;

    @Operation(summary = "添加公司")
    @RequestMapping(name = "/save",method = {RequestMethod.POST},
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public Result addCompany(@Validated(value = {AddGroup.class}) CompanyForm companyForm) {
        Company company = new Company();
        BeanUtils.copyProperties(companyForm,company);
        FileInfo businessLicenseFile = ossService.uploadFile(companyForm.getLicenseFile());
        FileInfo idCardFrontFile = ossService.uploadFile(companyForm.getIdCardFrontFile());
        FileInfo idCardBackFile = ossService.uploadFile(companyForm.getIdCardBackFile());
        company.setLicenseImg(businessLicenseFile.getUrl());
        company.setIdCardFront(idCardFrontFile.getUrl());
        company.setIdCardBack(idCardBackFile.getUrl());
        company.setStatus(0);
        companyService.save(company);
        return Result.success("添加成功");
    }


    @Operation(summary = "根据公司信息创建账号,创建部门")
    @PostMapping("/createAccount")
    public Result createAccount(@RequestParam Integer id) {
        LambdaQueryWrapper<Company> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Company::getId,id);
        Company company = companyService.getOne(wrapper);
        if(company == null){
            return Result.failed("公司不存在");
        }
        LambdaQueryWrapper<SysDept> wrapperDept = new LambdaQueryWrapper<>();
        wrapperDept.eq(SysDept::getName,company.getName());
        SysDept sysDept = sysDeptService.getOne(wrapperDept);

        //根据公司信息创建部门
        DeptForm deptForm = new DeptForm();
        deptForm.setName(company.getName());
        deptForm.setParentId(0L);
        deptForm.setStatus(1);
        sysDeptService.saveDept(deptForm);


        //把公司id和角色id关联起来
        sysUserRoleService.saveUserRoles(company.getId(), Collections.singletonList(companyRole));


        //根据公司信息创建账号
        UserForm userForm = new UserForm();
        userForm.setUsername(company.getMobile());
        userForm.setNickname(company.getName());
        userForm.setMobile(company.getMobile());
        userForm.setGender(1);
        userForm.setEmail(company.getEmail());
        userForm.setDeptId(sysDept.getId());

        sysUserService.saveUser(userForm);
        return Result.success("创建成功");

    }
    @PostMapping("/updateCompanyStatus")
    @Operation(summary = "更新公司状态")
    public Result updateCompanyStatus(@RequestBody RealCopanyRequest request) {
        String email = request.getEmail();
        String frontFileUrl = request.getFrontFile();
        String backFileUrl = request.getBackFile();
        String businessFile = request.getBusinessFile();

        // 查询公司信息
        LambdaQueryWrapper<Company> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Company::getEmail, email);
        Company company = companyService.getOne(queryWrapper);

        if (company == null) {
            return Result.failed("未找到对应的公司信息");
        }
        try {
            // 调用身份证信息提取验证服务
            String extractedResult;
            // 调用营业执照识别服务
            String businessResult;
            // 创建变量 在识别进行赋值 以便后方进行插入数据库操作
            String frontName;
            String frontID;
            String companyNameStr;
            try {
                // 身份证识别
                extractedResult = baiduAIService.validateIdCard(frontFileUrl, backFileUrl);
                // 提取身份证信息
                JSONObject extractedJson = JSONUtil.parseObj(extractedResult);
                // 解析得到返回值中的json对象
                JSONObject frontResult = extractedJson.getJSONObject("words_result");
                // 解析得到姓名json对象
                JSONObject frontNameObj = frontResult.getJSONObject("姓名");
                // 从json对象中获取words（姓名） 并转换为string类型
                frontName = frontNameObj.getStr("words");

                // 解析得到姓名json对象
                JSONObject frontIDObj = frontResult.getJSONObject("公民身份号码");
                // 从json对象中获取words（姓名） 并转换为string类型
                frontID = frontIDObj.getStr("words");


                // 营业执照识别
                businessResult = baiduAIService.businessRecognition(businessFile);
                // 获取营业执照信息
                JSONObject businessJson = JSONUtil.parseObj(businessResult);
                // 解析得到返回值中的json对象
                JSONObject business = businessJson.getJSONObject("words_result");
                //解析得到法人json对象
                JSONObject businessName = business.getJSONObject("法人");
                // 从json对象中获取words（姓名） 并转换为string类型
                String businessNameStr = businessName.getStr("words");
                //解析得到法人json对象
                JSONObject companyName = business.getJSONObject("单位名称");
                // 从json对象中获取words（姓名） 并转换为string类型
                companyNameStr = companyName.getStr("words");


                // 判断身份证和营业执照信息是否一致
                if (!frontName.equals(businessNameStr)) {
                    company.setStatus(2);
                    companyService.updateById(company);
                    return Result.failed("身份证姓名与营业执照法人代表姓名不一致，请重新上传。");
                }
            } catch (Exception e) {
                e.printStackTrace();
                company.setStatus(2);
                companyService.updateById(company);
                return Result.failed("企业信息提取失败: " + e.getMessage());
            }
            // 更新公司信息
            //更新身份证正反面照片
            company.setIdCardFront(frontFileUrl);
            company.setIdCardBack(backFileUrl);
            // 更新法人姓名及身份证号码
            company.setLegalName(frontName);
            company.setIdCardNo(frontID);
            // 更新营业执照照片
            company.setLicenseImg(businessFile);
            // 更新公司名称
            company.setName(companyNameStr);
            // 更新状态
            company.setStatus(1);
            // 获取当前系统时间
            LocalDateTime updateTime = LocalDateTime.now();
            //更新修改时间
            company.setUpdateTime(updateTime);
            companyService.updateById(company);


            return Result.success("企业认证成功");
        } catch (Exception e) {
            company.setStatus(2);
            companyService.updateById(company);
            e.printStackTrace();
            return Result.failed("企业认证失败: " + e.getMessage());
        }

    }

    @Operation(summary = "多条件分页查询")
    @PostMapping("/search")
    public Result searchPage(@RequestBody CompanyPageQuery query) {
        PageVO<CompanyVO> pageVo = companyService.search(query);
        return Result.success(pageVo);
    }
    @Operation(summary = "企业多条件分页查询")
    @PostMapping("/list")
    public Result list(@RequestBody CompanyQueys companyQueys){
        IPage<Company> companyIPage = new Page<>(companyQueys.getPage(), companyQueys.getSize());
        LambdaQueryWrapper<Company> queryWrapper = new LambdaQueryWrapper<>();
        // 公司名称
        queryWrapper.like(
                StringUtils.isNotBlank(companyQueys.getName()),
                Company::getName,
                companyQueys.getName());
        // 法人姓名
        queryWrapper.like(
                StringUtils.isNotBlank(companyQueys.getLegalName()),
                Company::getLegalName,
                companyQueys.getLegalName());
        // 身份证号码
        queryWrapper.like(
                StringUtils.isNotBlank(companyQueys.getIdCardNo()),
                Company::getIdCardNo,
                companyQueys.getIdCardNo());
        // 手机号码
        queryWrapper.like(
                StringUtils.isNotBlank(companyQueys.getMobile()),
                Company::getMobile,
                companyQueys.getMobile());
        // 邮箱
        queryWrapper.like(
                StringUtils.isNotBlank(companyQueys.getEmail()),
                Company::getEmail,
                companyQueys.getEmail());
        // 公司地址
        queryWrapper.like(
                StringUtils.isNotBlank(companyQueys.getAddress()),
                Company::getAddress,
                companyQueys.getAddress());
        // 创建时间
        queryWrapper.between(
                companyQueys.getStartTime() != null && companyQueys.getEndTime() != null,
                Company::getCreateTime,
                companyQueys.getStartTime(),
                companyQueys.getEndTime());
        // 执行查询
        IPage<Company> companyResult = companyService.page(companyIPage, queryWrapper);

        //获取总记录数
        long total = companyResult.getTotal();
        // 获取当前页数据列表
        List<Company> records = companyResult.getRecords();
        // 封装返回结果
        PageVO pageVO = new PageVO(total, records);
        return Result.success(pageVO);
    }

    @Operation(summary = "获取公司购买服务列表")
    @GetMapping("/serviceList")
    public Result serviceList(){
        LambdaQueryWrapper<Company> queryWrapper = new LambdaQueryWrapper<>();
        // 将服务天数不为空的查询出来
        queryWrapper.isNotNull(Company::getDaysRemaining);
        Company company = companyService.getOne(queryWrapper);
        return Result.success(company);
    }
}
